<template>
  <div style="max-width: 800px; margin: 40px auto;">
    <el-card shadow="hover">
      <template #header>
        <span style="font-size: 20px; font-weight: bold;">订单详情</span>
      </template>
      <div v-if="order && order.order">
        <!-- 收货信息 -->
        <el-descriptions title="收货信息" :column="1" border style="margin-bottom: 20px;">
          <el-descriptions-item label="收货人">{{ order.receiverName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ order.receiverPhone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ order.shippingAddress || '-' }}</el-descriptions-item>
        </el-descriptions>
        <!-- 订单信息 -->
        <el-descriptions title="订单信息" :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="订单号">{{ order.order.orderSn }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ order.order.createTime }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">{{ statusText(order.order.status) }}</el-descriptions-item>
          <el-descriptions-item label="总金额">
            <span style="color: #F56C6C; font-weight: bold;">￥{{ order.order.totalAmount && order.order.totalAmount.toFixed ? order.order.totalAmount.toFixed(2) : order.order.totalAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ order.order.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
        <!-- 商品明细 -->
        <el-table :data="order.items || []" style="width: 100%; margin-bottom: 16px;">
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="productPrice" label="单价" width="100">
            <template #default="scope">
              ￥{{ scope.row.productPrice && scope.row.productPrice.toFixed ? scope.row.productPrice.toFixed(2) : scope.row.productPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column label="小计" width="100">
            <template #default="scope">
              ￥{{ (scope.row.productPrice * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <!-- 操作按钮 -->
        <div style="margin-top: 24px; text-align: right;">
          <el-button v-if="order.order.status === 'UNPAID'" type="primary" @click="showPayDialog = true">去支付</el-button>
          <el-button v-if="order.order.status === 'UNPAID'" type="danger" @click="cancelOrder">取消订单</el-button>
          <el-button v-if="order.order.status === 'PAID'" type="warning" @click="showRefundDialog = true">申请退款</el-button>
          <el-button v-if="order.order.status === 'SHIPPED'" type="success" @click="confirmOrder">确认收货</el-button>
        </div>
      </div>
      <div v-else style="text-align: center; color: #bbb; padding: 40px;">订单不存在</div>
    </el-card>
    <!-- 支付弹窗 -->
    <el-dialog v-model="showPayDialog" title="选择支付方式" width="400px">
      <el-radio-group v-model="payMethod">
        <el-radio label="余额">余额支付</el-radio>
        <el-radio label="支付宝">支付宝（模拟）</el-radio>
        <el-radio label="微信">微信（模拟）</el-radio>
      </el-radio-group>
      <template #footer>
        <el-button @click="showPayDialog = false">取消</el-button>
        <el-button type="primary" @click="doPay">支付</el-button>
      </template>
    </el-dialog>
    <!-- 申请退款弹窗 -->
    <el-dialog v-model="showRefundDialog" title="申请退款" width="400px">
      <el-form :model="refundForm">
        <el-form-item label="原因">
          <el-input v-model="refundForm.reason" type="textarea" placeholder="请输入退款原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRefundDialog = false">取消</el-button>
        <el-button type="danger" @click="doRefund">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useUserStore } from '@/stores/userStore'
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const order = ref(null)
const showPayDialog = ref(false)
const payMethod = ref('余额')
const showRefundDialog = ref(false)
const refundForm = ref({ reason: '' })

function statusText(status) {
  switch (status) {
    case 'UNPAID': return '待付款'
    case 'PAID': return '已付款'
    case 'SHIPPED': return '已发货'
    case 'COMPLETED': return '已完成'
    case 'CANCELLED': return '已取消'
    case 'REFUNDING': return '退款中'
    case 'REFUNDED': return '已退款'
    default: return status
  }
}

function fetchOrderDetail() {
  request.get(`/api/order/${route.params.orderId}`).then(res => {
    if (res.success) {
      order.value = res.data
    }
  })
}

async function doPay() {
  if (payMethod.value === '余额' && userStore.balance < order.value.order.totalAmount) {
    ElMessage.error('余额不足，无法支付！')
    return
  }
  await ElMessageBox.confirm('确定要支付该订单吗？', '提示', { type: 'warning' })
  if (payMethod.value === '余额') {
    userStore.deductBalance(order.value.order.totalAmount, `支付订单${order.value.order.orderSn}`)
  }
  const res = await request.post(`/api/order/${order.value.order.orderId}/pay`, { payMethod: payMethod.value })
  if (res.success) {
    ElMessage.success('支付成功！')
    showPayDialog.value = false
    fetchOrderDetail()
  } else {
    ElMessage.error(res.message || '支付失败')
  }
}

async function cancelOrder() {
  await ElMessageBox.confirm('确定要取消该订单吗？', '提示', { type: 'warning' })
  const res = await request.post(`/api/order/${order.value.order.orderId}/cancel`)
  if (res.success) {
    ElMessage.success('订单已取消')
    fetchOrderDetail()
  } else {
    ElMessage.error(res.message || '取消失败')
  }
}

async function confirmOrder() {
  await ElMessageBox.confirm('确认已收到货物？', '提示', { type: 'warning' })
  const res = await request.post(`/api/order/${order.value.order.orderId}/confirm`)
  if (res.success) {
    ElMessage.success('已确认收货')
    fetchOrderDetail()
  } else {
    ElMessage.error(res.message || '操作失败')
  }
}

async function doRefund() {
  if (!refundForm.value.reason) {
    ElMessage.error('请填写退款原因')
    return
  }
  await ElMessageBox.confirm('确定要申请退款吗？', '提示', { type: 'warning' })
  const res = await request.post(`/api/order/${order.value.order.orderId}/refund`, { reason: refundForm.value.reason })
  if (res.success) {
    ElMessage.success('退款申请已提交')
    showRefundDialog.value = false
    fetchOrderDetail()
  } else {
    ElMessage.error(res.message || '申请失败')
  }
}

onMounted(fetchOrderDetail)
</script> 